package com.gainloop.Adapters;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.gainloop.R;
import com.gainloop.Api.Entity.User;
import com.gainloop.Listeners.PeopleItemListener;
import com.gainloop.Utils.ImageThreadLoader;
import com.gainloop.Utils.ImageThreadLoader.ImageLoadedListener;

public class UserAdapter extends ArrayAdapter<User> {

	private ArrayList<User> items;

	public UserAdapter(Context context, int textViewResourceId,
			ArrayList<User> items) {
		super(context, textViewResourceId, items);
		this.items = items;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.user_item, null);
		}
		User item = items.get(position);
		if (item != null) {
			final ImageView profile = (ImageView) v
					.findViewById(R.id.userItemProfileImg);
			TextView username = (TextView) v
					.findViewById(R.id.userItemUsername), location = (TextView) v
					.findViewById(R.id.userItemLocation), helps = (TextView) v
					.findViewById(R.id.userItemHelps);

			try {
//				URL newurl = new URL(
//						"http://graph.facebook.com/" + item.getFbId() + "/picture?type=square");
//				Bitmap bitmap = BitmapFactory.decodeStream(newurl
//						.openConnection().getInputStream());
//				profile.setImageBitmap(bitmap);
				
				Bitmap cachedImage = ImageThreadLoader.GetInstance().loadImage("http://graph.facebook.com/" + item.getFbId() + "/picture?type=square", 
						new ImageLoadedListener() {
					public void imageLoaded(Bitmap imageBitmap) {
						profile.setImageBitmap(imageBitmap);
						notifyDataSetChanged();                
					}
				});
				if(cachedImage != null)
					profile.setImageBitmap(cachedImage);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			v.setOnClickListener(new PeopleItemListener(item, this)) ;
			/*{
				
				@Override
				public void onClick(View v) {
					Intent intent=new Intent(UserAdapter.this.getContext(),GainPage.class)
					.putExtra(Constants.listTypeParam, ListType.USER)
					.putExtra(Constants.userParam, user.);
				WishList.this.startActivity(intent);
				}
			})*/
			username.setText(item.getName());
			//content.setText(item.getContentShort());
			location.setText(item.getLocationName());
			helps.setText("" + item.getResolvedNum());
		}
		return v;
	}
}